package com.eva.baidulibrary;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLngBounds;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * Class description
 *
 * @author GUXIA318
 * @date 2015-09-11 11:15
 */
public abstract class CustomizedOverlayManager implements BaiduMap.OnMarkerClickListener{
    protected BaiduMap map = null;
    protected List<Overlay> overlays = null;
    private List<OverlayOptions> options = null;

    public CustomizedOverlayManager(BaiduMap map) {
        this.map = map;
        if (this.options == null) {
            this.options = new ArrayList();
        }

        if (this.overlays == null) {
            this.overlays = new ArrayList();
        }
    }

    public abstract List<OverlayOptions> getOverlayOptions();

    public final void addToMap() {
        if (this.map != null) {
            this.removeFromMap();
            List overlayOptions = getOverlayOptions();
            if (overlayOptions != null) {
                this.options.addAll(overlayOptions);
            }

            Iterator iterator = this.options.iterator();
            while (iterator.hasNext()) {
                OverlayOptions options = (OverlayOptions) iterator.next();
                this.overlays.add(map.addOverlay(options));
            }
        }
    }

    public final void removeFromMap() {
        if (this.map != null) {
            Iterator iterator = this.overlays.iterator();

            while (iterator.hasNext()) {
                Overlay overlay = (Overlay) iterator.next();
                overlay.remove();
            }

            this.overlays.clear();
            this.options.clear();
        }
    }

    public void zoomToSpan() {
        if (this.map != null) {
            if (this.overlays.size() > 0) {
                LatLngBounds.Builder builder = new LatLngBounds.Builder();
                Iterator iterator = this.overlays.iterator();

                while (iterator.hasNext()) {
                    Overlay overlay = (Overlay) iterator.next();
                    if (overlay instanceof Marker) {
                        builder.include(((Marker) overlay).getPosition());
                    }
                }

                this.map.setMapStatus(MapStatusUpdateFactory.newLatLngBounds(builder.build()));
            }
        }
    }

}
